package com.training.controller;

import com.training.entity.OfflinePractice;
import com.training.entity.PracticeEnrollment;
import com.training.entity.Student;
import com.training.entity.User;
import com.training.service.OfflinePracticeService;
import com.training.service.PracticeEnrollmentService;
import com.training.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/student/practice")
public class StudentPracticeController {

    private final OfflinePracticeService practiceService;
    private final PracticeEnrollmentService enrollmentService;
    private final StudentService studentService;

    @Autowired
    public StudentPracticeController(OfflinePracticeService practiceService, PracticeEnrollmentService enrollmentService, StudentService studentService) {
        this.practiceService = practiceService;
        this.enrollmentService = enrollmentService;
        this.studentService = studentService;
    }

    /**
     * Handles GET requests for /student/practice/browse to show all available practices.
     * @param keyword Optional search keyword.
     * @param model Model to pass data to the view.
     * @param session HttpSession to get user info.
     * @return The name of the view template to render.
     */
    @GetMapping("/browse")
    public String browsePractices(@RequestParam(value = "keyword", required = false) String keyword, Model model, HttpSession session) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) {
            return "redirect:/login";
        }

        // For now, searching across all teachers. A null teacherId in the service method means fetch all.
        List<OfflinePractice> practices = practiceService.searchPracticesByTeacher(null, keyword);
        model.addAttribute("practices", practices);
        model.addAttribute("loggedInUser", user);
        return "practice-browse"; // Renders practice-browse.html
    }

    /**
     * Handles GET requests to view a single practice and its enrollment form.
     * @param id The ID of the practice to view.
     * @param model Model to pass data to the view.
     * @param session HttpSession to get user info.
     * @return The name of the view template.
     */
    @GetMapping("/view/{id}")
    public String viewPractice(@PathVariable("id") Long id, Model model, HttpSession session) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) {
            return "redirect:/login";
        }

        OfflinePractice practice = practiceService.getPracticeById(id);
        model.addAttribute("practice", practice);
        model.addAttribute("enrollment", new PracticeEnrollment());
        model.addAttribute("loggedInUser", user);
        return "practice-student-view"; // Renders practice-student-view.html
    }

    /**
     * Handles POST requests to enroll in a practice.
     * @param enrollment The enrollment data from the form.
     * @param session HttpSession to get user info.
     * @param redirectAttributes For flash messages.
     * @return A redirect string.
     */
    @PostMapping("/enroll")
    public String enroll(@ModelAttribute("enrollment") PracticeEnrollment enrollment, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) {
            return "redirect:/login";
        }

        Student student = studentService.getStudentByUserId(user.getId());
        enrollment.setStudentId(student.getId());

        try {
            enrollmentService.enroll(enrollment);
            redirectAttributes.addFlashAttribute("successMessage", "报名成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "报名失败: " + e.getMessage());
        }
        return "redirect:/student/practice/view/" + enrollment.getPracticeId();
    }

    /**
     * Handles GET requests to show the student's own enrollments.
     * @param model Model to pass data to the view.
     * @param session HttpSession to get user info.
     * @return The name of the view template.
     */
    @GetMapping("/my-enrollments")
    public String myEnrollments(Model model, HttpSession session) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null || !"STUDENT".equals(user.getRole())) {
            return "redirect:/login";
        }

        Student student = studentService.getStudentByUserId(user.getId());
        List<PracticeEnrollment> enrollments = enrollmentService.getMyEnrollments(student.getId());
        model.addAttribute("enrollments", enrollments);
        model.addAttribute("loggedInUser", user);
        return "my-enrollments"; // Renders my-enrollments.html
    }

    /**
     * Handles POST requests to cancel an enrollment.
     * @param enrollmentId The ID of the enrollment to cancel.
     * @param session HttpSession to get user info.
     * @param redirectAttributes For flash messages.
     * @return A redirect string.
     */
    @PostMapping("/my-enrollments/cancel/{id}")
    public String cancelEnrollment(@PathVariable("id") Long enrollmentId, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("loggedInUser");
        if (user == null) {
            return "redirect:/login";
        }

        Student student = studentService.getStudentByUserId(user.getId());
        try {
            enrollmentService.cancelEnrollment(enrollmentId, student.getId());
            redirectAttributes.addFlashAttribute("successMessage", "已成功取消报名。");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "操作失败: " + e.getMessage());
        }
        return "redirect:/student/practice/my-enrollments";
    }
}